package com.syn.vr.activity;

import android.text.TextUtils;
import android.view.View;

import androidx.activity.result.ActivityResult;

import com.gaoyi.basemodule.baseUtil.NetworkUtil;
import com.gaoyi.basemodule.baseUtil.SPUtil;
import com.gaoyi.basemodule.baseUtil.StringUtil;
import com.gaoyi.basemodule.baseUtil.ToastUtil;
import com.gaoyi.basemodule.baseUtil.WindowUtil;
import com.gaoyi.basemodule.baseact.BaseActivity;
import com.gaoyi.basemodule.basebean.Event;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.syn.vr.BR;
import com.syn.vr.R;
import com.syn.vr.constant.Constants;
import com.syn.vr.databinding.ActivityLoginBinding;
import com.syn.vr.util.RSAUtil;
import com.syn.vr.vm.LoginViewModel;

import java.util.Map;

public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> {

    @Override
    protected void event(Event event) {

    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {

    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        WindowUtil.setWindowDecorView(this);
        mBinding.btnLogin.setOnClickListener((this::login));
//        mBinding.tvForget.setOnClickListener(this);
    }

    private void login(View v) {
        if (StringUtil.isEmpty(mViewModel.getAccount().getValue())) {
            ToastUtil.showToast(R.string.p_user_hint);
            return;
        }
        String pwd = mViewModel.getPwd().getValue();
        if (StringUtil.isEmpty(pwd)) {
            ToastUtil.showToast(R.string.p_pwd_hint);
            return;
        }
        if (NetworkUtil.isConnected()) {
            v.setEnabled(false);
            mViewModel.login(mBinding.cbxRem.isChecked());
        } else {
            ToastUtil.showToast(R.string.network_error);
        }
    }

    @Override
    protected int initVariable() {
        return BR.data;
    }

    @Override
    protected void initLiveData() {
        mViewModel.getResultCode().observe(this, integer -> mBinding.btnLogin.setEnabled(true));
    }

    @Override
    protected void initData() {
        if (StringUtil.isEmpty(mViewModel.getAccount().getValue())) {
            mViewModel.setAccount(SPUtil.getInstance().getString(SPName.ACCOUNT));
        }
        String pwd = SPUtil.getInstance().getString(SPName.PASSWORD);
        if (!TextUtils.isEmpty(pwd)) {
            String[] split = pwd.split(Constants.SPLIT);
            pwd = RSAUtil.decipher(split[0], split[1]);
            mViewModel.setPwd(pwd);
            mBinding.cbxRem.setChecked(true);
        }
    }
}